import IProps from '@/model/other/IProps'
import { debounce } from '@/util/CommonUtil'
import { Button, Form, SideSheet, Space } from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import { Dispatch, SetStateAction, useRef } from 'react'

interface ICSearchForm<T> extends IProps {
  sideSheetVisible: boolean
  setSideSheetVisible: Dispatch<SetStateAction<boolean>>
  getTableData: (values: any) => void
  setSearchForm: Dispatch<SetStateAction<T>>
  width?: number
}

export default function CSearchForm<T>(props: ICSearchForm<T>) {
  const searchFormApi = useRef<FormApi>()

  return (
    <SideSheet
      title="搜索"
      visible={props.sideSheetVisible}
      onCancel={() => {
        props.setSideSheetVisible(false)
      }}
      keepDOM
      width={props.width ? props.width : 380}
      footer={
        <Space className="flex jc-c">
          <Button
            onClick={() => {
              searchFormApi.current?.reset() // 重置表单
              props.getTableData(searchFormApi.current?.getValues()) // 执行搜索
            }}
          >
            重置
          </Button>
          <Button
            type="tertiary"
            onClick={() => {
              props.setSideSheetVisible(false)
            }}
          >
            关闭
          </Button>
        </Space>
      }
    >
      <Form
        onValueChange={(values: any) => {
          debounce(() => {
            props.setSearchForm(values)
            props.getTableData(values)
          })
        }}
        getFormApi={(api) => (searchFormApi.current = api)}
      >
        {/* 子组件 */}
        {props.children}
      </Form>
    </SideSheet>
  )
}
